import React, { useState, useEffect, useRef } from 'react';
import { Button } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';
import Draggable from 'react-draggable';
import { getDraftWithUrls, DraftWithUrlsResponse } from '@/services/draftWithUrls';
import './VideoPreview.css';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '@/store';
import { eventBus } from '@/utils/eventBus';
import { setCursorPosition, setTotalDuration, setCurrentTime, setPlaying } from '@/store/timeline';
import { createDebounce } from '@/utils/debounceUtils';
import VideoLayer from './preview/layer/VideoLayer';
import ImageLayer from './preview/layer/ImageLayer';
import TextLayer from './preview/layer/TextLayer';

const VideoPreview: React.FC = () => {
    const canvasRef = useRef<HTMLDivElement>(null);
    const draggableRef = useRef<HTMLDivElement>(null);

    // 当前草稿信息
    const currentDraft = useSelector((state: RootState) => state.drafts.currentDraft);
    const dispatch = useDispatch();
    // 游标位置
    const cursorPosition = useSelector((state: RootState) => state.timeline.cursorPosition);
    const totalDuration = useSelector((state: RootState) => state.timeline.totalDuration);
    const currentTime = useSelector((state: RootState) => state.timeline.currentTime);
    const pixelsPerSecond = useSelector((state: RootState) => state.timeline.pixelsPerSecond);

    // 是否正在播放
    const [draftData, setDraftData] = useState<DraftWithUrlsResponse['data'] | null>(null);
    const [loading, setLoading] = useState(true);
    const [isPlaying, setIsPlaying] = useState(false);
    const [showControls, setShowControls] = useState(false);
    const animationFrameRef = useRef<number | null>(null);
    const hideTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    const isDraggingRef = useRef<boolean>(false);
    const lastCursorTimeRef = useRef<number>(0);
    const debouncedDragEndRef = useRef<any>(null);
    const isPlayingRef = useRef<boolean>(false);
    // 获取草稿数据
    useEffect(() => {
        const fetchDraftData = async () => {
            if (!currentDraft?.id) {
                return;
            }
            try {
                setLoading(true);
                const response = await getDraftWithUrls(currentDraft.id);
                setDraftData(response);
            } catch (error) {
                // 静默处理错误
            } finally {
                setLoading(false);
            }
        };

        fetchDraftData();
    }, [currentDraft?.id]);

    // 监听更新预览视频事件
    useEffect(() => {
        const handleUpdatePreview = () => {
            // 停止播放视频
            setIsPlaying(false);
            dispatch(setCurrentTime(0));

            // 停止时间动画
            if (animationFrameRef.current) {
                cancelAnimationFrame(animationFrameRef.current);
                animationFrameRef.current = null;
            }

            // 重新初始化预览
            if (draftData) {
                // 清理当前预览
                cleanupSimplePreview();

                // 延迟重新初始化，确保清理完成
                setTimeout(() => {
                    initSimplePreview();
                }, 100);
            }
        };

        // 监听片段配置更新事件
        const handleSegmentConfigUpdate = () => {
            console.log('收到片段配置更新事件，重新获取草稿数据');
            // 重新获取草稿数据
            if (currentDraft?.id) {
                const fetchDraftData = async () => {
                    try {
                        setLoading(true);
                        const response = await getDraftWithUrls(currentDraft.id);
                        setDraftData(response);
                        console.log('草稿数据已更新');
                    } catch (error) {
                        console.error('重新获取草稿数据失败:', error);
                    } finally {
                        setLoading(false);
                    }
                };
                fetchDraftData();
            }
        };

        // 监听更新预览视频事件
        eventBus.on('updatePreviewVideo' as any, handleUpdatePreview);
        // 监听片段配置更新事件
        eventBus.on('segmentConfig:updated' as any, handleSegmentConfigUpdate);

        // 清理监听器
        return () => {
            eventBus.off('updatePreviewVideo' as any, handleUpdatePreview);
            eventBus.off('segmentConfig:updated' as any, handleSegmentConfigUpdate);
        };
    }, [draftData, currentDraft?.id]);

    // 监听播放时间变化，同步视频播放
    useEffect(() => {
        if (draftData) {
            // 预览时间同步
        }
    }, [currentTime, draftData]);

    // 创建防抖函数（只创建一次）
    useEffect(() => {
        if (!debouncedDragEndRef.current) {
            debouncedDragEndRef.current = createDebounce(
                () => {
                    isDraggingRef.current = false;
                    // 拖动完成后，发送事件通知VideoPreview更新帧
                    eventBus.emit('cursor:drag:frame:update' as any, {});
                },
                { delay: 100 }
            ); // 100ms防抖
        }
    }, []);

    // 监听Cursor拖动事件，停止播放
    useEffect(() => {
        const handleCursorDragStart = () => {
            isDraggingRef.current = true;
            // 如果正在播放，停止播放
            if (isPlayingRef.current) {
                pausePlayback();
            }
        };

        const handleCursorDragEnd = () => {
            if (debouncedDragEndRef.current) {
                debouncedDragEndRef.current.execute();
            }
        };

        const handleFrameUpdate = () => {
            // 拖动完成后，更新预览到当前时间
            if (draftData) {
                // 预览时间更新
            }
        };

        // 监听Cursor拖动事件
        eventBus.on('cursor:drag:start' as any, handleCursorDragStart);
        eventBus.on('cursor:drag:end' as any, handleCursorDragEnd);
        eventBus.on('cursor:drag:frame:update' as any, handleFrameUpdate);

        return () => {
            eventBus.off('cursor:drag:start' as any, handleCursorDragStart);
            eventBus.off('cursor:drag:end' as any, handleCursorDragEnd);
            eventBus.off('cursor:drag:frame:update' as any, handleFrameUpdate);
        };
    }, []); // 移除所有依赖，避免无限循环

    // 计算总时长和重叠时长
    const calculateTotalDuration = (draftData: DraftWithUrlsResponse['data']) => {
        if (!draftData?.script_content?.tracks) {
            return 0;
        }
        const tracks = draftData.script_content.tracks;
        let maxEndTime = 0;
        for (const track of tracks) {
            for (const segment of track.segments) {
                const targetTimerange = segment.target_timerange;
                if (targetTimerange) {
                    // 微秒转换为毫秒
                    const startMs = targetTimerange.start / 1000;
                    const durationMs = targetTimerange.duration / 1000;
                    const endTime = startMs + durationMs;
                    maxEndTime = Math.max(maxEndTime, endTime);
                }
            }
        }
        return maxEndTime;
    };

    // 播放控制函数
    const togglePlay = () => {
        if (isPlaying) {
            pausePlayback();
        } else {
            startPlayback();
        }
    };

    // 开始播放
    const startPlayback = () => {
        setIsPlaying(true);
        isPlayingRef.current = true;
        dispatch(setPlaying(true));
        // 从当前时间开始播放，而不是从0开始
        lastCursorTimeRef.current = currentTime;
        // 启动时间动画
        startTimeAnimation();
    };

    // 暂停播放
    const pausePlayback = () => {
        setIsPlaying(false);
        isPlayingRef.current = false;
        dispatch(setPlaying(false));
        // 停止时间动画
        if (animationFrameRef.current) {
            cancelAnimationFrame(animationFrameRef.current);
            animationFrameRef.current = null;
        }
    };

    // 时间动画函数
    const startTimeAnimation = () => {
        // 先清理之前的动画帧
        if (animationFrameRef.current) {
            cancelAnimationFrame(animationFrameRef.current);
            animationFrameRef.current = null;
        }

        const startTime = Date.now();
        const startCurrentTime = currentTime; // 记录当前时间作为起始点

        const animate = () => {
            // 如果正在拖动Cursor，暂停动画
            if (isDraggingRef.current) {
                return;
            }

            // 检查是否还在播放状态 - 使用ref来避免闭包问题
            if (!isPlayingRef.current) {
                return;
            }

            const elapsed = Date.now() - startTime;
            const newTime = Math.min(startCurrentTime + elapsed, totalDuration);
            dispatch(setCurrentTime(newTime));
            dispatch(setCursorPosition(200 + (newTime / 1000) * pixelsPerSecond));

            if (newTime >= totalDuration) {
                // 播放完毕，停止所有动画
                setIsPlaying(false);
                isPlayingRef.current = false;
                dispatch(setPlaying(false));
                if (animationFrameRef.current) {
                    cancelAnimationFrame(animationFrameRef.current);
                    animationFrameRef.current = null;
                }
                return;
            }
            // 继续动画循环
            animationFrameRef.current = requestAnimationFrame(animate);
        };

        animationFrameRef.current = requestAnimationFrame(animate);
    };

    // 触发更新预览视频事件（用于测试）
    const triggerUpdatePreview = () => {
        eventBus.emit('updatePreviewVideo' as any, {});
    };

    // 格式化时间显示
    const formatTime = (timeMs: number) => {
        const seconds = Math.floor(timeMs / 1000);
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    };

    // 初始化预览
    const initSimplePreview = () => {
        console.log('初始化预览');
        // 计算总时长
        if (draftData) {
            const duration = calculateTotalDuration(draftData);
            dispatch(setTotalDuration(duration));
        }
    };

    // 清理预览
    const cleanupSimplePreview = () => {
        console.log('清理预览');
        // 清理预览相关资源
    };

    // 组件挂载时自动启动预览
    useEffect(() => {
        if (draftData && !loading) {
            // 使用 setTimeout 确保状态更新后再初始化
            setTimeout(() => {
                initSimplePreview();
            }, 100);
        }

        // 组件卸载时清理
        return () => {
            // 停止所有动画
            if (animationFrameRef.current) {
                cancelAnimationFrame(animationFrameRef.current);
                animationFrameRef.current = null;
            }
            // 清理预览
            cleanupSimplePreview();
            // 清理定时器
            if (hideTimeoutRef.current) {
                clearTimeout(hideTimeoutRef.current);
            }
            // 清理防抖函数
            if (debouncedDragEndRef.current && debouncedDragEndRef.current.cancel) {
                debouncedDragEndRef.current.cancel();
            }
        };
    }, [draftData, loading]);

    if (loading) {
        return (
            <div className="video-preview-container">
                <div className="loading-wrapper">
                    <div className="loading-text">加载中...</div>
                </div>
            </div>
        );
    }

    if (!draftData) {
        return (
            <div className="video-preview-container">
                <div className="error-wrapper">
                    <div className="error-text">数据加载失败</div>
                </div>
            </div>
        );
    }

    // 处理鼠标进入事件
    const handleMouseEnter = () => {
        setShowControls(true);
        if (hideTimeoutRef.current) {
            clearTimeout(hideTimeoutRef.current);
            hideTimeoutRef.current = null;
        }
    };

    // 处理鼠标离开事件
    const handleMouseLeave = () => {
        // 如果正在播放，不隐藏控制面板
        if (isPlaying) {
            return;
        }

        hideTimeoutRef.current = setTimeout(() => {
            setShowControls(false);
        }, 1000); // 1秒后隐藏
    };
    // 获取画布尺寸信息 - 使用新的数据结构
    const canvasConfig = draftData?.canvas_config;
    const canvasWidth = canvasConfig?.width || 1920;
    const canvasHeight = canvasConfig?.height || 1080;

    return (
        <div className={`video-preview-container ${isPlaying ? 'playing' : ''}`} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
            {/* 可拖拽的尺寸显示 */}
            <Draggable bounds="parent" defaultPosition={{ x: 300, y: -160 }} nodeRef={draggableRef}>
                <div ref={draggableRef} className="canvas-size-info draggable">
                    <span className="size-label">画布尺寸</span>
                    <span className="size-value">
                        {canvasWidth} × {canvasHeight}
                    </span>
                </div>
            </Draggable>

            <div className="preview-wrapper">
                <div ref={canvasRef} className="preview-container">
                    {draftData ? (
                        <>
                            {/* 视频图层 - 基础图层，zIndex较低 */}
                            <VideoLayer draftData={draftData} canvasWidth={canvasWidth} canvasHeight={canvasHeight} />

                            {/* 图片图层 - 叠加在视频之上，zIndex较高 */}
                            <ImageLayer draftData={draftData} canvasWidth={canvasWidth} canvasHeight={canvasHeight} />

                            {/* 文本图层 - 叠加在图片之上，zIndex最高 */}
                            <TextLayer draftData={draftData} canvasWidth={canvasWidth} canvasHeight={canvasHeight} />
                        </>
                    ) : (
                        <div className="preview-content">
                            <div className="preview-text">视频预览</div>
                        </div>
                    )}
                </div>

                {/* 简化的播放控制面板 */}
                <div className={`simple-playback-controls ${showControls ? 'show' : 'hide'}`}>
                    <div className="simple-controls-row">
                        {/* 播放/暂停按钮 */}
                        <div className="play-button-container">
                            <Button type="text" icon={isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />} onClick={togglePlay} className="play-pause-button" />
                        </div>

                        {/* 时间显示 */}
                        <div className="time-display-container">
                            <span className="time-display">
                                {formatTime(currentTime)} / {formatTime(totalDuration)}
                            </span>
                        </div>

                        {/* 测试按钮 - 触发更新预览视频事件 */}
                        <div className="test-button-container">
                            <Button type="text" onClick={triggerUpdatePreview} style={{ color: '#ffffff', fontSize: '12px' }}>
                                更新预览
                            </Button>
                            <Button type="text" onClick={() => dispatch(setCursorPosition(Math.random() * 1000))} style={{ color: '#ffffff', fontSize: '12px', marginLeft: '8px' }}>
                                移动游标 ({Math.round(cursorPosition)}px)
                            </Button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default VideoPreview;
